﻿using System;
using System.Data;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using LMSemir.DAC;
using LMSemir.Common;
namespace LMSemir.API
{
    public partial class get : System.Web.UI.Page
    {
        protected string writeXml = string.Empty;
        public readonly string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["LMSemirConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            int userID = WebUtils.GetPramaValue("uid", 0);
            int teeID = WebUtils.GetPramaValue("tid", 0);
            this.Response.ContentType = "text/xml";

            string method = this.Request["m"] == null ? "" : this.Request["m"];
            switch (method.ToLower())
            {
                case "gettidlist"://获取作品相近的左右50个ID列表
                    int tid = Convert.ToInt32(WebUtils.GetPramaValue("tid", "0"));
                    string cid = WebUtils.GetPramaValue("cid", "");
                    this.GetTeeIdList(tid, cid);
                    break;
                case "gettotalcount"://获取作品总数
                    this.Response.Write(TEEUtil.generateTeeXML(TeeDataAccess.getTeeTotalCount()));
                    break;
                case "addbyflash":
                    string teeNameFlash = WebUtils.GetPramaValue("name", "");
                    string teeAuthorFlash = WebUtils.GetPramaValue("author", "");
                    string teeAddressFlash = WebUtils.GetPramaValue("addr", "");
                    string teeVideoPathFlash = WebUtils.GetPramaValue("videopath", "");
                    string teeEmailFlash = WebUtils.GetPramaValue("email", "");
                    string teeMobileFlash = WebUtils.GetPramaValue("mobile", "");
                    string teeIntroFlash = WebUtils.GetPramaValue("intro", "");
                    string teeSourceFlash = WebUtils.GetPramaValue("source", "");
                    string teePhotoNameFlash = WebUtils.GetPramaValue("imgname", "");
                    string teePhotoPathFlash = WebUtils.GetPramaValue("imgpath", "");
                    int teeStatusFlash = WebUtils.GetPramaValue("st", 0);
                    try
                    {
                        LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addbyflash=>" + HttpContext.Current.Request.QueryString.ToString());

                        if (!string.IsNullOrEmpty(teeNameFlash) && !string.IsNullOrEmpty(teeAuthorFlash))
                        {
                            this.addTeeInfoByFlash(teeNameFlash, teeAuthorFlash, teeAddressFlash,
                                teeVideoPathFlash, Request.InputStream, teeEmailFlash, teeMobileFlash,
                                teeIntroFlash, teeStatusFlash, teeSourceFlash, userID,
                            teePhotoNameFlash, teePhotoPathFlash);
                        }
                        else
                        {
                            string strElementValue = teeNameFlash + " is null;" + " and " + teeAuthorFlash + "is null";

                            this.Response.Write(TEEUtil.generateTeeXML(-1, "error", strElementValue));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.GetInstance().WriteDebugLog("error:addteeinfo=>" + ex.Message);
                    }
                    break;
                case "addteeinfobydouban":
                    string db_teeName = WebUtils.GetPramaValue("name", "");
                    string db_teeAuthor = WebUtils.GetPramaValue("author", "");
                    string db_teeAddress = WebUtils.GetPramaValue("addr", "");
                    string db_teeVideoPath = WebUtils.GetPramaValue("videopath", "");
                    string db_teeEmail = WebUtils.GetPramaValue("email", "");
                    string db_teeMobile = WebUtils.GetPramaValue("mobile", "");
                    string db_teeIntro = WebUtils.GetPramaValue("intro", "");
                    string db_teeSource = WebUtils.GetPramaValue("source", "");
                    string db_teePhotoName = WebUtils.GetPramaValue("imgname", "");
                    string db_teePhotoPath = WebUtils.GetPramaValue("imgpath", "");
                    int db_teeStatus = db_teeSource == "douban" ? 4 : WebUtils.GetPramaValue("st", 0);
                    try
                    {
                        LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addteeinfobydouban=>" + HttpContext.Current.Request.QueryString.ToString());

                        if (!string.IsNullOrEmpty(db_teeName) && !string.IsNullOrEmpty(db_teeAuthor))
                        {
                            string localPath = this.Server.MapPath("~/images/temp/");
                            if (!Directory.Exists(localPath))
                            {
                                Directory.CreateDirectory(localPath);
                            }
                            string tempFileName = localPath + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-douban.jpg";

                            string tempPhotoPath = ImageUtils.saveImgByPath(db_teePhotoPath, tempFileName, "http://www.douban.com/");
                            string tempUrl = "http://" + Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(tempPhotoPath);


                            this.addTeeInfoByTuDou(db_teeName, db_teeAuthor, db_teeAddress, db_teeVideoPath, tempUrl,
                            db_teeEmail, db_teeMobile, db_teeIntro, db_teeStatus, db_teeSource, userID,
                            db_teePhotoName, tempUrl);
                        }
                        else
                        {
                            string strElementValue = "teeName is null or teeAuthor is null ";

                            this.Response.Write(TEEUtil.generateTeeXML(-1, "error", strElementValue));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.GetInstance().WriteDebugLog("error:addteeinfo=>" + ex.Message);
                    }

                    break;
                case "addteeinfobytudou":
                    string td_teeName = WebUtils.GetPramaValue("name", "");
                    string td_teeAuthor = WebUtils.GetPramaValue("author", "");
                    string td_teeAddress = WebUtils.GetPramaValue("addr", "");
                    string td_teeVideoPath = WebUtils.GetPramaValue("videopath", "");
                    string td_teeEmail = WebUtils.GetPramaValue("email", "");
                    string td_teeMobile = WebUtils.GetPramaValue("mobile", "");
                    string td_teeIntro = WebUtils.GetPramaValue("intro", "");
                    string td_teeSource = WebUtils.GetPramaValue("source", "");
                    string td_teePhotoName = WebUtils.GetPramaValue("imgname", "");
                    string td_teePhotoPath = WebUtils.GetPramaValue("imgpath", "");
                    int td_teeStatus = td_teeSource == "tudou" ? 4 : WebUtils.GetPramaValue("st", 0);
                    try
                    {
                        LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addteeinfobytudou=>" + HttpContext.Current.Request.QueryString.ToString());

                        if (!string.IsNullOrEmpty(td_teeName) && !string.IsNullOrEmpty(td_teeAuthor))
                        {
                            this.addTeeInfoByTuDou(td_teeName, td_teeAuthor, td_teeAddress, td_teeVideoPath, td_teePhotoPath,
                            td_teeEmail, td_teeMobile, td_teeIntro, td_teeStatus, td_teeSource, userID,
                            td_teePhotoName, td_teePhotoPath);
                        }
                        else
                        {
                            string strElementValue = "teeName is null or teeAuthor is null ";

                            this.Response.Write(TEEUtil.generateTeeXML(-1, "error", strElementValue));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.GetInstance().WriteDebugLog("error:addteeinfo=>" + ex.Message);
                    }
                    break;
                case "addteeinfo":
                    string teeName = WebUtils.GetFormValue("name", "");
                    string teeAuthor = WebUtils.GetFormValue("author", "");
                    string teeAddress = WebUtils.GetFormValue("addr", "");
                    string teeVideoPath = WebUtils.GetFormValue("videopath", "");
                    string teeEmail = WebUtils.GetFormValue("email", "");
                    string teeMobile = WebUtils.GetFormValue("mobile", "");
                    string teeIntro = WebUtils.GetFormValue("intro", "");
                    string teeSource = WebUtils.GetFormValue("source", "");
                    string teePhotoName = WebUtils.GetFormValue("imgname", "");
                    string teePhotoPath = WebUtils.GetFormValue("imgpath", "");
                    int teeStatus = teeSource == "tudou" ? 4 : WebUtils.GetFormValue("st", 0);//如果是土豆过来的数据，则作品已审核

                    try
                    {
                        LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addteeinfo=>" + HttpContext.Current.Request.QueryString.ToString());
                        if (!string.IsNullOrEmpty(teeName) && !string.IsNullOrEmpty(teeAuthor))
                        {
                            HttpPostedFile hpf = Request.Files["Filedata"];

                            this.addTeeInfo(teeName, teeAuthor, teeAddress, teeVideoPath, hpf,
                            teeEmail, teeMobile, teeIntro, teeStatus, teeSource, userID,
                            teePhotoName, teePhotoPath);
                        }
                        else
                        {
                            string strElementValue = teeName + " is null;" + " and " + teeAuthor + "is null";

                            this.Response.Write(TEEUtil.generateTeeXML(-1, "error", strElementValue));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.GetInstance().WriteDebugLog("error:addteeinfo=>" + ex.Message);
                    }
                    break;
                case "getteeinfobyid":
                    this.getTeeInfoById(teeID);
                    break;
                case "setvotecountbyid":
                    int voteCount = WebUtils.GetPramaValue("votecount", 0);
                    this.setVoteCountById(teeID);
                    break;
                case "searchteebykeyword":
                    string keyword = WebUtils.GetPramaValue("q", "");
                    this.searchTeeByKeyword(keyword);
                    break;
                case "getteelistbycid":
                    int categoryID = WebUtils.GetPramaValue("cid", 0);
                    this.getTeeListByCID(categoryID);
                    break;
                case "gettop20byday":
                    string currentDay = WebUtils.GetPramaValue("date", DateTime.Now.ToString("yyyy-MM-dd"));
                    Response.Write(TEEUtil.generateTeeXML(TeeDataAccess.getTop20ByDay(currentDay)));
                    break;
                case "gettop6bymonth":
                    string month = WebUtils.GetPramaValue("month", DateTime.Now.ToString("yyyy-MM"));
                    Response.Write(TEEUtil.generateTeeXML(TeeDataAccess.getTop6ByMonth(month)));
                    break;
                case "getteelistbypage":
                    int pageIndex = WebUtils.GetPramaValue("p", 1);
                    int pageSize = WebUtils.GetPramaValue("num", 20);
                    string orderType = WebUtils.GetPramaValue("sort", "");
                    int rowCount = 0;

                    DataTable dt = TeeDataAccess.getTeeListByPage(pageIndex, pageSize, orderType, out rowCount);
                    Response.Write(TEEUtil.generateTeeXML(dt, rowCount));
                    break;
            }
        }

        private void GetTeeIdList(int tid, string cid)
        {
            int categoryID = 0;
            DataTable dtIdList = new DataTable();
            if (!string.IsNullOrEmpty(cid))
            {
                categoryID = Convert.ToInt32(cid.Substring(12, 1));
            }
            dtIdList = TeeDataAccess.getTeeIdList(tid, categoryID);

            if (dtIdList.Rows.Count > 0)
            {
                string strIds = string.Empty;
                foreach (DataRow dr in dtIdList.Rows)
                {
                    strIds += dr["tid"].ToString() + ",";
                }
                string strIdList = strIds.Substring(0, strIds.Length - 1);
                this.Response.Write(TEEUtil.generateTeeXML(1, "ids", strIdList));
            }
        }
        //get tee's data by categoryid
        private void getTeeListByCID(int categoryID)
        {
            try
            {
                if (categoryID != 0)
                {
                    DataTable dtCategory = TeeDataAccess.getTeeListByCID(categoryID);
                    Response.Write(TEEUtil.generateTeeXML(dtCategory));
                }
            }
            catch (Exception ex)
            {
                LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>getTeeListByCID" + ex.Message);
                throw;
            }
        }
        //search keywords by user's post words
        private void searchTeeByKeyword(string query)
        {
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(query))
            {
                try
                {
                    int teeStatus = this.GetOrderId(query);
                    if (teeStatus == 0)
                    {
                        dt = TeeDataAccess.searchTeeByKeyword(query);
                    }
                    else
                    {
                        dt = TeeDataAccess.searchTeeByOrder(teeStatus);
                    }
                    Response.Write(TEEUtil.generateTeeXML(dt));
                }
                catch (Exception ex)
                {
                    LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>searchTeeByKeyword" + ex.ToString());
                }
            }
        }
        private int GetOrderId(string query)
        {
            int teeStatus = 0;
            string[] strArray = new string[] { "semir_order_1", "semir_order_2", "semir_order_3", "semir_order_4", "semir_order_5", "semir_order_7" };
            for (int i = 0; i < strArray.Length; i++)
            {
                if (query.Contains(strArray[i]))
                {
                    teeStatus = Convert.ToInt32(query.Substring(12, 1));
                    break;
                }
            }
            return teeStatus;
        }
        //save tee's votecount by teeID
        private void setVoteCountById(int teeID)
        {
            try
            {
                int isSuccess = TeeDataAccess.setVoteCountByIds(teeID, WebUtils.UserClientIP);
                this.Response.Write(TEEUtil.generateTeeXML(isSuccess));
            }
            catch (Exception ex)
            {
                LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>getTeeListByCID" + ex.Message);
                throw;
            }
        }

        //new tee's data
        public void addTeeInfoByTuDou(string Name, string Author, string Address, string VideoPath, string imgUrl,
           string Email, string Mobile, string Intro, int Status, string Source, int UserID,
            string PhotoName, string PhotoPath)
        {
            try
            {
                if (null != Name && null != Author &&
                    Name.Length != 0 && Author.Length != 0)
                {
                    //存储数据到DB
                    int teeID = 0;
                    int isSuccess = TeeDataAccess.addTeeInfo(Name, Author, Address, VideoPath, Email, Mobile,
                            Intro, imgUrl, imgUrl, imgUrl, Status, Source,
                            UserID, PhotoName, PhotoPath, out teeID);
                    this.Response.Write(TEEUtil.generateTeeXML(isSuccess, "teeid", teeID.ToString()));
                }
            }
            catch (Exception ex)
            {
                LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addTeeInfo=>" + ex.Message);
                throw;
            }
        }

        //new tee's data
        public void addTeeInfo(string Name, string Author, string Address, string VideoPath, HttpPostedFile file,
           string Email, string Mobile, string Intro, int Status, string Source, int UserID, string PhotoName, string PhotoPath)
        {
            try
            {
                if (null != Name && null != Author &&
                    Name.Length != 0 && Author.Length != 0)
                {
                    Stream s = file.InputStream;

                    MemoryStream streamSmall = ImageUtils.ResizeImage(s, 40, 48);
                    MemoryStream streamMidd = ImageUtils.ResizeImage(s, 150, 180);

                    #region 检查图片存放路径
                    string phsisPath = Server.MapPath("~/images/");
                    string yearPath = phsisPath + DateTime.Now.Year + "\\";
                    if (!Directory.Exists(yearPath))
                    {
                        Directory.CreateDirectory(yearPath);
                    }
                    string monthPath = yearPath + DateTime.Now.Month + "\\";
                    if (!Directory.Exists(monthPath))
                    {
                        Directory.CreateDirectory(monthPath);
                    }
                    string dayPath = monthPath + DateTime.Now.Day + "\\";
                    if (!Directory.Exists(dayPath))
                    {
                        Directory.CreateDirectory(dayPath);
                    }
                    string smallDir = dayPath + "s\\";
                    string middDir = dayPath + "m\\";
                    string largeDir = dayPath + "l\\";
                    if (!Directory.Exists(smallDir))
                    {
                        Directory.CreateDirectory(smallDir);
                    }
                    if (!Directory.Exists(middDir))
                    {
                        Directory.CreateDirectory(middDir);
                    }
                    if (!Directory.Exists(largeDir))
                    {
                        Directory.CreateDirectory(largeDir);
                    }
                    #endregion

                    //获取最终小,中,大图片存储路径
                    string strSmallPath = smallDir + DateTime.Now.Hour + DateTime.Now.Minute +
                          DateTime.Now.Second + PhotoName + ".jpg";
                    string strMiddPath = middDir + DateTime.Now.Hour + DateTime.Now.Minute +
                          DateTime.Now.Second + PhotoName + ".jpg";
                    string strLargePath = largeDir + DateTime.Now.Hour + DateTime.Now.Minute +
                       DateTime.Now.Second + PhotoName + ".jpg";

                    #region 存储图片并新增数据
                    if (ImageUtils.saveImgByPath(strSmallPath, streamSmall))
                    {
                        if (ImageUtils.saveImgByPath(strMiddPath, streamMidd))
                        {
                            //存储大图
                            file.SaveAs(strLargePath);

                            //拼接图片地址
                            strSmallPath = "http://" + HttpContext.Current.Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(strSmallPath);
                            strMiddPath = "http://" + HttpContext.Current.Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(strMiddPath);
                            strLargePath = "http://" + HttpContext.Current.Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(strLargePath);

                            //存储数据到DB
                            int teeID = 0;
                            int isSuccess = TeeDataAccess.addTeeInfo(Name, Author, Address, VideoPath, Email, Mobile,
                                    Intro, strSmallPath, strMiddPath, strLargePath, Status, Source,
                                    UserID, PhotoName, PhotoPath, out teeID);
                            this.Response.Write(TEEUtil.generateTeeXML(isSuccess, "teeid", teeID.ToString()));

                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addTeeInfo=>" + ex.Message);
                throw;
            }
        }

        public void addTeeInfoByFlash(string Name, string Author, string Address, string VideoPath, Stream stream,
          string Email, string Mobile, string Intro, int Status, string Source, int UserID, string PhotoName, string PhotoPath)
        {
            try
            {
                if (null != Name && null != Author &&
                    Name.Length != 0 && Author.Length != 0)
                {
                    Stream s = stream;
                    MemoryStream streamSmall = ImageUtils.ResizeImage(s, 40, 48);
                    MemoryStream streamMidd = ImageUtils.ResizeImage(s, 150, 180);

                    #region 检查图片存放路径
                    string phsisPath = Server.MapPath("~/images/");
                    string yearPath = phsisPath + DateTime.Now.Year + "\\";
                    if (!Directory.Exists(yearPath))
                    {
                        Directory.CreateDirectory(yearPath);
                    }
                    string monthPath = yearPath + DateTime.Now.Month + "\\";
                    if (!Directory.Exists(monthPath))
                    {
                        Directory.CreateDirectory(monthPath);
                    }
                    string dayPath = monthPath + DateTime.Now.Day + "\\";
                    if (!Directory.Exists(dayPath))
                    {
                        Directory.CreateDirectory(dayPath);
                    }
                    string smallDir = dayPath + "s\\";
                    string middDir = dayPath + "m\\";
                    string largeDir = dayPath + "l\\";
                    if (!Directory.Exists(smallDir))
                    {
                        Directory.CreateDirectory(smallDir);
                    }
                    if (!Directory.Exists(middDir))
                    {
                        Directory.CreateDirectory(middDir);
                    }
                    if (!Directory.Exists(largeDir))
                    {
                        Directory.CreateDirectory(largeDir);
                    }
                    #endregion

                    //获取最终小,中,大图片存储路径
                    string strSmallPath = smallDir + DateTime.Now.Hour + DateTime.Now.Minute +
                          DateTime.Now.Second + PhotoName + ".jpg";
                    string strMiddPath = middDir + DateTime.Now.Hour + DateTime.Now.Minute +
                          DateTime.Now.Second + PhotoName + ".jpg";
                    string strLargePath = largeDir + DateTime.Now.Hour + DateTime.Now.Minute +
                       DateTime.Now.Second + PhotoName + ".jpg";

                    #region 存储图片并新增数据
                    if (ImageUtils.saveImgByPath(strSmallPath, streamSmall))
                    {
                        if (ImageUtils.saveImgByPath(strMiddPath, streamMidd))
                        {
                            //存储大图
                            if (ImageUtils.saveImgByPath(strLargePath, stream))
                            {
                                //拼接图片地址
                                strSmallPath = "http://" + HttpContext.Current.Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(strSmallPath);
                                strMiddPath = "http://" + HttpContext.Current.Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(strMiddPath);
                                strLargePath = "http://" + HttpContext.Current.Request.Url.Host + "/2011tees" + ImageUtils.getImageUrl(strLargePath);

                                //存储数据到DB
                                int teeID = 0;
                                int isSuccess = TeeDataAccess.addTeeInfo(Name, Author, Address, VideoPath, Email, Mobile,
                                        Intro, strSmallPath, strMiddPath, strLargePath, Status, Source,
                                        UserID, PhotoName, PhotoPath, out teeID);

                                this.Response.Write(TEEUtil.generateTeeXML(isSuccess, "teeid", teeID.ToString()));
                            }

                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>addTeeInfo=>" + ex.Message);
            }
        }

        //get tee's data by teeID
        private void getTeeInfoById(int teeId)
        {
            try
            {
                DataTable dt = TeeDataAccess.getTeeInfoById(teeId);
                this.Response.Write(TEEUtil.generateTeeXML(dt));
            }
            catch (Exception ex)
            {
                LogUtil.GetInstance().WriteDebugLog(DateTime.Now.ToString() + "=>getTeeInfoById" + ex.Message);
                throw;
            }
        }
    }
}